// pages/addAdress/addAdress.js
var app = getApp();
var model = require('../../utils/model/model.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    region: ['江苏省', '连云港市', '连云区'],
    isCanSubmit:false,
    userInfo: '',
    addrInfoLen:'',
    isEdit: false,
    editId:'',
    formData:{
      userId:'',
      receiverName:"",
      receiverPhone:"",
      backupPhone:"",
      type:0,
      address:"",
      province:'江苏省',
      city:'连云港市',
      county:'连云区'
    },
    productId: '',
    amount: '',
    modelData: {
      showModal: false,
      signle: true,
      signleBtnTxt: "确定",
      content: '',
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    model.init.apply(this, ['modelData']);
    var address = wx.getStorageSync('address');
    this.setData({
      productId: address.productId,
      amount: address.amount,
      propertyId: address.propertyId,
      'formData.userId': JSON.parse(wx.getStorageSync('userInfo')).id,
      userInfo: JSON.parse(wx.getStorageSync('userInfo'))
    })
    this.getAddrInfo();
    if (options.editData!=undefined){
      var data = JSON.parse(options.editData);
      for (var j in data){
        if (this.data.formData[j]!=undefined){
          this.data.formData[j] = data[j];
        }
      }
      this.setData({
        isEdit: true,
        editId: data.id,
        region: data.region,
        formData: this.data.formData,
        isCanSubmit:true
      })
      wx.setNavigationBarTitle({
        title: '编辑地址'
      })
    }
  },
  checkReg: function (data) {
    var flag = true;
    for (var key in data) {
      if (data[key]) {
        if (key == 'receiverPhone' || key == 'backupPhone'){
          var reg = new RegExp("^1[34578][0-9]{9}$");
          if (!reg.test(data[key])) {
            flag = false;
            this.setData({
              'modelData.showModal': true,
              'modelData.content': '请输入正确的手机号'
            });
            return;
          }
        }
      }
    }
    return flag;
  },
  // 获取收货地址信息
  getAddrInfo: function(){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'userAddress/page',
      data: {userId: this.data.userInfo.id},
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        _this.setData({
          addrInfoLen: res.data.data.page.totalNumber
        })
        if (_this.data.addrInfoLen == 0){
          _this.setData({
            ['formData.type']: 1
          })
        }
      }
    })
  },
  bindRegionChange: function (e) {
    let province = 'formData.province';
    let city = 'formData.city';
    let county = 'formData.county';
    this.setData({
      [province]: e.detail.value[0],
      [city]: e.detail.value[1],
      [county]: e.detail.value[2],
    })
  },
  changeInput:function(e){
    this.data.formData[e.currentTarget.dataset.value]=e.detail.value;
    var flag=true;
    for(var j in this.data.formData){
      if (j != 'backupPhone'){
        if (this.data.formData[j] === "") {
          flag = false;
        }
      }
    }
    this.setData({
      isCanSubmit:flag
    })
    
  },
  switchChange: function(e){
    if(e.detail.value){
      this.setData({
        ['formData.type']: 1
      })
    }
    else{
      this.setData({
        ['formData.type']: 0
      })
    }
  },
  // 保存并提交数据
  saveSubmit: function(){
    var _this = this;
    if (this.data.isCanSubmit){
      if (this.checkReg(this.data.formData) == true){
        if (_this.data.isEdit) {
          _this.data.formData.id = _this.data.editId;
          wx.request({
            url: app.globalData.httpApiCar + 'userAddress/update',
            data: _this.data.formData,
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              if (res.data.success) {
                if (_this.data.formData.type == 1) {
                  _this.changeDefault(res.data.data)
                }
                else {
                  wx.redirectTo({
                    url: '/pages/confirmOrder/confirmOrder?adressData=' + JSON.stringify(_this.data.formData) + '&productId=' + _this.data.productId + ' &amount=' + _this.data.amount,
                  })
                }
              }
              else {
                wx.showToast({
                  title: res.data.error,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        }
        else {
          wx.request({
            url: app.globalData.httpApiCar + 'userAddress/save',
            data: _this.data.formData,
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              if (_this.data.formData.type == 1) {
                _this.changeDefault(res.data.data)
              }
              else {
                wx.redirectTo({
                  url: '/pages/confirmOrder/confirmOrder?adressData=' + JSON.stringify(_this.data.formData) + '&productId=' + _this.data.productId + ' &amount=' + _this.data.amount,
                })
              }
            }
          })
        }
      }
    }
  },
  // 选择默认地址
  changeDefault: function (id) {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'userAddress/default',
      data: {
        id: id,
        userId: _this.data.userInfo.id
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        wx.redirectTo({
          url: '/pages/confirmOrder/confirmOrder?adressData=' + JSON.stringify(_this.data.formData) + '&productId=' + _this.data.productId + ' &amount=' + _this.data.amount,
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})